﻿using Summer.WeiXin.Core;
using Summer.WeiXin.Utility;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;

namespace WebSite.Handler
{
    /// <summary>
    /// WeiXinHandler 的摘要说明
    /// </summary>
    public class WeiXinHandler : IHttpHandler
    {

        public string token = ConfigurationManager.AppSettings["token"];
        private string appid = ConfigurationManager.AppSettings["appid"].ToString();
        private string appsecret = ConfigurationManager.AppSettings["appsecret"].ToString();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string result = string.Empty;
            string echostr = RequestQueryString.GetQueryString("echostr");
            string method = context.Request.HttpMethod.ToUpper();
            if (method == "GET")
            {
                if (CheckSignature())
                {
                    result = echostr;
                }
            }
            if (method == "POST")
            {
                Message me = MessageService.GetMessage();

                if (!string.IsNullOrEmpty(me.EventName))
                {
                    if (me.EventName.Trim() == "subscribe")
                    {
                        string content = "/:rose欢迎关注开心一刻。";
                        result = new MessageHandler().sendTextMessage(me, content);
                    }//关注  
                } 
            }
            else
            {
                result = "无法处理";
            }
            context.Response.Write(result);

        }


        /// <summary>
        /// GET校验
        /// </summary>
        /// <returns></returns>

        public bool CheckSignature()
        {
            string signature = RequestQueryString.GetQueryString("signature");
            string timestamp = RequestQueryString.GetQueryString("timestamp");
            string nonce = RequestQueryString.GetQueryString("nonce");

            List<string> list = new List<string>();
            list.Add(token);
            list.Add(timestamp);
            list.Add(nonce);

            list.Sort();

            string input = string.Empty;
            foreach (var item in list)
            {
                input += item;
            }

            string new_signature = SecurityUtility.SHA1Encrypt(input);

            if (new_signature == signature)
            {
                return true;
            }
            else
            {
                return false;
            }


        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}